package cn.stronglink.suite.core.shiro;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;

import cn.stronglink.asset.model.User;
import cn.stronglink.asset.module.sys.user.service.UserService;
import cn.stronglink.suite.core.util.SecurityUtil;
import cn.stronglink.suite.core.util.WebUtil;

public class Realm extends AuthorizingRealm {

	private final Logger logger = LogManager.getLogger();

	@Autowired
	private RedisOperationsSessionRepository sessionRepository;

	@Autowired
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User params = new User();
		params.setAccount(token.getUsername());	
		StringBuilder sb = new StringBuilder(100);
		for (int i = 0; i < token.getPassword().length; i++) {
			sb.append(token.getPassword()[i]);
		}
		params.setPassword(sb.toString());
		User user = userService.login(params);
		if (user != null) {
			if(user.getStatus() == 2){
				throw new LockedAccountException();
			}else if(user.getStatus() == 3){
				throw new DisabledAccountException();
			}else{
				WebUtil.saveCurrentUser(user.getId());
				WebUtil.saveCurrentUserName(user.getName());
				WebUtil.setSession("isAdmin", user.isAdmin());
				AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getAccount(), user.getPassword(),
						user.getName());
				return authcInfo;
			}
		}else{
			logger.warn("USER [{}] PASSWORD IS WRONG: {}", token.getUsername(), token.getPassword().toString());
			return null;
		}

	}

	/** 保存session */
	private void saveSession(User user) {

	}

}
